// pages/resume/resume.js
import request from '../../utils/request';
Page({
  data: {
    textBox1Content: '',
    textBox2Content: '',
    textBox3Content: '',
    textBox4Content: '',
    isLoggedIn: false,
    hasResume: false,
    resume: {},
    schoolNames: [],
    departmentNames: [],
    selectedSchool: {},
    selectedDepartment: {},
    student_name: '',
    gender: '',
    birth_date: '',
    phone: '',
    email: '',
    school_name: '',
    major: '',
    skills_certificates: '',
    experience: '',
    self_evaluation: '',
    remark: ''
  },

  /**
   * 生命周期函数--监听页面加载
   * 页面加载时调用 fetchSchools 方法获取学校信息，并检查本地存储中是否有 token，
   * 如果有则设置 isLoggedIn 状态为 true，表示用户已登录。
   */
  onLoad: function () {
    this.fetchSchools();
    const token = wx.getStorageSync('token');
    if (token) {
      this.setData({
        isLoggedIn: true
      });
    }
  },

  // 完善后的获取学校列表接口
  fetchSchools: function () {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.showToast({
        title: '请重新登录',
        icon: 'none'
      })
      return wx.navigateTo({
        url: '/pages/login/login',
      })
    }
    wx.showLoading({
      title: '加载学校列表...',
      mask: true
    });
    wx.request({
      url: 'http://localhost:8090/xh/admin/schools/list',
      method: 'GET',

      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        // console.log('学校完整响应:', res);
        // 强化校验逻辑
        if (res.statusCode === 200) {
          const responseData = res.data;

          // 处理不同数据结构
          const rawData = responseData.data || responseData;

          if (Array.isArray(rawData)) {
            // 严格字段校验
            const validData = rawData.filter(item =>
              item && item.schoolsName && typeof item.schoolsName === 'string'
            );

            this.setData({
              schools: validData,
              schoolNames: validData.map(x => x.schoolsName.trim())
            });
            return;
          }
        }

        // 统一错误处理
        wx.showToast({
          title: `数据异常 (${res.statusCode})`,
          icon: 'none'
        });
      },
      fail: (err) => {
        console.error('请求详情:', err);
        wx.showToast({
          title: err.errMsg.includes('timeout') ? '请求超时' : '网络错误',
          icon: 'none'
        });
      },
      complete: () => wx.hideLoading()
    });
  },

  bindSchoolChange: function (e) {
    const index = e.detail.value;
    const selectedSchool = this.data.schools[index];
    // console.log('选中的学校对象:', selectedSchool);
    this.setData({
      selectedSchool: selectedSchool,
      selectedDepartment: {},
      departments: []
    });
    
    this.fetchDepartments(selectedSchool.schoolsID);
  },

  // 完善后的获取院系列表接口
  fetchDepartments: function(schoolsID) {
    // 参数有效性校验
    if (!schoolsID || typeof schoolsID !== 'number') {
      wx.showToast({ title: '学校ID无效', icon: 'none' });
      return;
    }
    console.log('传递的学校ID:', schoolsID, '类型:', typeof schoolsID);
    // ...
  
    const token = wx.getStorageSync('token');
    // Token失效处理
    if (!token) {
      wx.showToast({ title: '请重新登录', icon: 'none' });
      return wx.reLaunch({ url: '/pages/login/login' });
    }
  
    wx.showLoading({
      title: '加载中...',
      mask: true // 防止误操作
    });
  
    wx.request({
      url: 'http://localhost:8090/xh/admin/departments',
      data: { id: schoolsID },
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        // console.log('院系完整响应:', res);
        // console.log('院系响应数据格式:', typeof res.data);
        // console.log('院系响应数据内容:', JSON.stringify(res.data));
    
        
        // 强化校验逻辑
        if (res.statusCode === 200) {
          const responseData = res.data;
          
          // 处理嵌套数据结构
          const rawData = responseData.data || responseData;
          
          if (Array.isArray(rawData)) {
            // 严格字段校验
            const validData = rawData.filter(item => 
              item?.departmentName && typeof item.departmentName === 'string'
            );
            
            // 空数据兜底
            if (validData.length === 0) {
              return this.setData({ 
                departments: [],
                departmentNames: ['暂无院系数据'] 
              });
            }
  
            // 数据加工处理
            const departmentNames = validData
              .map(x => x.departmentName.trim())
              .filter(name => name.length > 0);
  
            this.setData({
              departments: validData,
              departmentNames: [...new Set(departmentNames)] // 去重处理
            });
            return;
          }
        }
        
        // 错误处理增强
        const errorMsg = res.data?.message || `数据异常(${res.statusCode})`;
        wx.showToast({ title: errorMsg, icon: 'none' });
      },
      fail: (err) => {
        console.error('[NETWORK ERROR]', err);
        const msg = err.errMsg.includes('timeout') ? '请求超时' : '网络连接异常';
        wx.showToast({ title: msg, icon: 'none' });
      },
      complete: () => wx.hideLoading()
    });
  },

  bindDepartmentChange: function (e) {
    const index = e.detail.value;
    const selectedDepartment = this.data.departments[index];
    this.setData({
      selectedDepartment: selectedDepartment
    });
  },

  bindDateChange: function (e) {
    this.setData({
      birth_date: e.detail.value
    });
  },

  onShow() {
    const token = wx.getStorageSync('token');
    if (token) {
      this.setData({
        isLoggedIn: true
      });
    } else {
      this.setData({
        isLoggedIn: false
      });
    }
    const editedData = wx.getStorageSync('editedData');
    if (editedData) {
      const {
        id,
        content
      } = editedData;
      switch (id) {
        case 'textBox1':
          this.setData({
            textBox1Content: content
          });
          break;
        case 'textBox2':
          this.setData({
            textBox2Content: content
          });
          break;
        case 'textBox3':
          this.setData({
            textBox3Content: content
          });
          break;
        case 'textBox4':
          this.setData({
            textBox4Content: content
          });
          break;
      }
      wx.removeStorageSync('editedData');
    }
  },

  submitResume(e) {
    if (!this.data.isLoggedIn) {
      wx.showToast({
        title: '保存失败，请先登录后再保存',
        icon: 'none'
      });
      return;
    }
    const token = wx.getStorageSync('token');
    const formData = e.detail.value;
    // 确保技能证书、实习经历、自我评价和备注字段有值
    formData.skills_certificates = this.data.skills_certificates;
    formData.experience = this.data.experience;
    formData.self_evaluation = this.data.self_evaluation;
    formData.remark = this.data.remark;
    // 添加学校 ID 和院系 ID
    if (this.data.selectedSchool && this.data.selectedSchool.id) {
      formData.school_id = this.data.selectedSchool.id;
    }
    if (this.data.selectedDepartment && this.data.selectedDepartment.id) {
      formData.department_id = this.data.selectedDepartment.id;
    }

    wx.request({
      url: 'https://localhost:8090/xh/resume/saveResume',
      method: 'POST',
      data: formData,
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({
            title: '保存成功',
            icon: 'success'
          });
          this.setData({
            hasResume: true,
            resume: res.data.data
          });
        } else {
          wx.showToast({
            title: res.data.msg || '保存失败，请稍后重试',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },

  fetchResume() {
    const token = wx.getStorageSync('token');
    const wechat_openid = wx.getStorageSync('wechat_openid'); // 假设 wechat_openid 存储在本地
    wx.request({
      url: 'https://localhost:8090/xh/resume/getResume',
      method: 'GET',
      data: {
        wechat_openid
      },
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.code === 200 && res.data.data) {
          const resumeData = res.data.data;
          this.setData({
            hasResume: true,
            resume: resumeData,
            student_name: resumeData.student_name,
            gender: resumeData.gender,
            birth_date: resumeData.birth_date,
            phone: resumeData.phone,
            email: resumeData.email,
            school_id: resumeData.school_id,
            major: resumeData.major,
            skills_certificates: resumeData.skills_certificates,
            experience: resumeData.experience,
            self_evaluation: resumeData.self_evaluation,
            remark: resumeData.remark
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '获取简历信息失败',
          icon: 'none'
        });
      }
    });
  },

  editResume() {
    this.setData({
      hasResume: false
    });
  },

  goToEditPage(e) {
    const textBoxId = e.currentTarget.id;
    let content = '';
    switch (textBoxId) {
      case 'textBox1':
        content = this.data.skills_certificates;
        break;
      case 'textBox2':
        content = this.data.experience;
        break;
      case 'textBox3':
        content = this.data.self_evaluation;
        break;
      case 'textBox4':
        content = this.data.remark;
        break;
    }
    wx.navigateTo({
      url: `/pages/resume/edit/edit?id=${textBoxId}&content=${encodeURIComponent(content)}`
    });
  }
});